import MyForm from "./framework/common/components/MyForm";
import { useRequest, useUpdate } from "ahooks";
import FormSkeleton from "./components/FormSkeleton";
import Header from "./components/Header";
import Footer from "./components/Footer1/Footer1";
import { getQuery, isIE } from "./framework/common/utils";
import { getApprovalProcessInfo } from "./apis/flowInstance";
import { useSubscribe } from "./framework/common/eventBus";
import React, { Suspense, useEffect, useLayoutEffect, useRef, useState } from "react";
import { toggleMode } from "./framework/common/context/metadata-context";
import ApproveStepReadonly from "./RuntimeForm/ApproveStep/ApproveStepReadonly1";
import RelationProcess from "./RuntimeForm/RelationProcess1/RelationProcess1";
import { ConfigProvider, Spin } from "antd";
import zhCN from "antd/es/locale/zh_CN";
import clsx from "clsx";
import Service from "./components/Service";
import "./theme/newYear/approval.css";
import PointWrapper from "./RuntimeForm/PointWrapper";
import PrintPreview from "./PrintPreview";
import useScreenLock from "./framework/common/lifecycle/useScreenLock";
const RuntimeForm = React.lazy(() => import("./RuntimeForm")); //流程中心表单
const CustomForm = React.lazy(() => import("./RuntimeForm/CustomForm/CustomForm.js")); //外挂表单

function App() {
  let getProcessInfo;
  const query = getQuery();
  // let initialMode = "Display";
  //如果时发起流程或者审批流程，fixme: 后面根据url来判断
  let mode = 2; //2 审批中 ，1发起 重新发起 草稿 ,3 打印

  if (~window.location.pathname.indexOf("/flowinstance/approval/index")) {
    //审批
    mode = 2;
  } else if (~window.location.pathname.indexOf("/flowinstance/process/create")) {
    //发起
    mode = 1;
  } else if (~window.location.pathname.indexOf("/flowinstance/approval/preview")) {
    //打印
    mode = 3;
  }

  //前端调试发起页使用
  if (query.create == "1" || query.action == "create") {
    mode = 1;
  } else if (query.action == "print") {
    mode = 3;
  }

  getProcessInfo = getApprovalProcessInfo;

  const { data, error, loading } = useRequest(getProcessInfo, { defaultParams: [getQuery("string"), mode] });
  const updater = useUpdate();
  //////////////开发时切换模式用
  useSubscribe(toggleMode, () => {
    if (modeRef.current === "Display") modeRef.current = "Design";
    else if (modeRef.current === "Design") modeRef.current = "Display";
    updater({});
  });
  ///////////////end
  const modeRef = useRef("Display");

  useLayoutEffect(()=>{

    if(mode===3){
      document.querySelector("#root").classList.add("preview-design")
    }
  },[])

  useEffect(() => {
    if (mode === 1) {
      document.title = "创建流程";
    } else if (mode === 3) {
      document.title = "流程打印";
    } else if (data?.data?.tplData?.view_mode !== true) {
      document.title = "审批流程";
    } else {
      document.title = "查看流程";
    }
  }, [modeRef.current, mode, loading]);

  let isPrint=(mode === 3)
  if (loading || data == undefined) {
    //加载中返回骨架图
    return (
      <div className={clsx(isPrint&&"bg-gray-90")}>
        {/*流程标题*/}
        <Header mode={mode} loading={loading} data={data}></Header>
        {/* 打印模式不需要显示龙骨架图 */}
        { !isPrint ?<FormSkeleton></FormSkeleton>:<div style={{height:"calc(100vh - 50px)"}}></div>}
      </div>
    );
  }

  if (data.data.tplData.view_mode !== true) {

      modeRef.current = "Design"; //设计模式
  }  
  if (isPrint) {
    modeRef.current = "Print"; //打印模式
  }

  return (
    <ConfigProvider locale={zhCN}>
      <MyForm
        key={modeRef.current}
        mode={modeRef.current}
        initialFormState={data.data.tplData}
        params={data.data.params}
        // fixme: 目前打印的api缺少下面3个参数，需要后端加
        urlPrefix={data.data.urlPrefix}
        csrfToken={data.data.csrfToken}
        csrfParam={data.data.csrfParam}
      >
        {data !== undefined &&
          (isPrint ? (
            <PrintPreview mode={mode} tplData={data.data.tplData} params={data.data.params} data={data}></PrintPreview>
          ) : (
            <Content mode={mode} tplData={data.data.tplData} params={data.data.params} data={data}></Content>
          ))}
      </MyForm>
    </ConfigProvider>
  );
}

function Content({ mode, tplData, params, data }) {
  //显示隐藏发起表单
  const [hideFooter, setHideFooter] = useState(false);

  function toggleFooter() {
    setHideFooter(!hideFooter);
  }
  //表单锁
  const lockInfo = useScreenLock();

  let relative = "relative";
  let isInIE = isIE();
  if (isInIE) {
    relative = "";
  }
  return (
    <Spin spinning={lockInfo.spinning} tip={lockInfo?.tip} wrapperClassName="screen-locker">
      {/*流程标题区*/}
      <Header mode={mode} data={data}></Header>

      {/*内容区*/}
      <div className={clsx("w-full overflow-x-hidden overflow-y-auto main-content bg-gray-50 pt-4 pb-3", relative, hideFooter && "hideFooter")}>
        {/*IE专属Hack区*/}
        {isInIE && <div className="relative ieHackWrapper"></div>}
        <div
          className={clsx("pb-2 runtime-form relative w-1100px mx-auto mb-4 overflow-hidden transition-all duration-300 bg-white rounded px-30px", tplData.ApproveSteps.length <= 0 && "initiateForm")}
        >
          {/* 表单 */}
          {tplData.form.form_mode == 0 ? ( // =0流程中心表单 =1外挂表单
            <Suspense fallback={<FormSkeleton></FormSkeleton>}>
              <RuntimeForm></RuntimeForm>
            </Suspense>
          ) : (
            <Suspense fallback={<FormSkeleton></FormSkeleton>}>
              <CustomForm></CustomForm>
            </Suspense>
          )}

          {/*关联流程*/}
          <RelationProcess></RelationProcess>

          {/*审批流程只读 */}
          {tplData?.ApproveSteps?.length > 0 && <ApproveStepReadonly approveSteps={tplData?.ApproveSteps} tplData={tplData} params={params} model={"readonly"}></ApproveStepReadonly>}
        </div>
      </div>
      {/*审批要点*/}
      <PointWrapper></PointWrapper>
      <div className="leftCloud"></div>
      <div className="rightCloud"></div>

      {/* 客服 */}
      <Service></Service>

      {/*
       * 审批按钮区
       * tplData.ApproveSteps.length > 0 为审批中
       */}
      <Footer toggleFooter={toggleFooter} hideFooter={hideFooter}></Footer>
    </Spin>
  );
}

export default App;
